package com.videoplayer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.adapter.DownloadAdapter;
import com.adapter.DownloadEditAdapter;
import com.application.VideosList;
import com.entity.FileInfo;
import com.services.aidl.IDownLoadService;
import com.services.aidl.Queue;
import com.umeng.analytics.MobclickAgent;
import com.util.ConfirmDialog;
import com.util.DownloadDialog;
import com.util.FileHelper;
import com.util.MyToast;

public class DownLoadActivity extends Activity implements OnClickListener {

	private final int NORMAL = 0;
	private final int EDIT = 1;
	private int MODE = 0;
	private static final String SERVICE_ACTION = "com.service.download_service";
	// 服务接口
	private IDownLoadService downloadService;
	private ListView lvDownFiles;
	private ListView lvDownEditFiles;
	private List<FileInfo> downFilesList = new ArrayList<FileInfo>();
	private DownloadAdapter downAdapter;
	private DownloadEditAdapter downEditAdapter;
	private int count = 0;
	// 服务绑定器
	private String[] oriVideoUrl;
	private Button btnBcak;
	private Button btnModify;
	private Button btnEditBack;
	private Button btnEditDelete;
	private String title;
	private VideosList videoList;
	private boolean downflag;
	private List<Queue> downloadList = new ArrayList<Queue>();
	private ServiceConnection sConnect = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			downloadService = IDownLoadService.Stub.asInterface(service);
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MobclickAgent.onError(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		initAvtivity();
		// 绑定服务
		Intent intent = new Intent(SERVICE_ACTION);
		bindService(intent, sConnect, Context.BIND_AUTO_CREATE);

	}

	private void initAvtivity() {
		if (MODE == NORMAL) {
			NormalMode();
		} else {
			EditMode();
		}
	}

	private void NormalMode() {
		MODE = NORMAL;
		setContentView(R.layout.download);
		IntentFilter counterActionFilter = new IntentFilter(
				"com.services.download");
		registerReceiver(counterActionReceiver, counterActionFilter);
		lvDownFiles = (ListView) findViewById(R.id.lv_down_folder);
		videoList = (VideosList) DownLoadActivity.this.getApplication()
				.getApplicationContext();
		btnBcak = (Button) findViewById(R.id.btn_dwon_back);
		btnModify = (Button) findViewById(R.id.btn_modify);
		btnBcak.setOnClickListener(this);
		btnModify.setOnClickListener(this);
		getIntentValue();
		viewFiles(Environment.getExternalStorageDirectory()
				+ "/EazyPlay/download/");
		downAdapter = new DownloadAdapter(DownLoadActivity.this, downFilesList);
		lvDownFiles.setAdapter(downAdapter);
		lvDownFiles.setCacheColorHint(0);
		lvDownFiles.setOnItemClickListener(lvItemListener);
//		lvDownFiles.setOnItemLongClickListener(listviewOnLongClick);
		int count = 0;
		if (videoList.getDownloadList() != null) {
			count = videoList.getDownloadList().size();
		}
		if (downflag) {
			for (int i = count; i < oriVideoUrl.length + count; i++) {
				Queue queue = new Queue();
				queue.setId(i);
				queue.setName(title);
				queue.setSavePath(Environment.getExternalStorageDirectory()
						+ "/EazyPlay/download/"
						+ title.replaceAll("[\\p{Punct}\\p{Space}]+", "") + "/"
						+ title.replaceAll("[\\p{Punct}\\p{Space}]+", "") + "_"
						+ i + ".flv");
				queue.setUrl(oriVideoUrl[i - count]);
				queue.setDowningIntent("com.activityAction.download");
				downloadList.add(queue);
			}
		}
		onResume();
	}
	
	OnItemLongClickListener listviewOnLongClick = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			final ConfirmDialog dialog = new ConfirmDialog(
					DownLoadActivity.this, R.style.MyDialog, "是否停止下载该文件",
					oriVideoUrl.length);
			dialog.show();
			Button btnOk = (Button) dialog.findViewById(R.id.dialog_confirm_button_ok);
			return false;
		}
	};

	private void EditMode() {
		MODE = EDIT;
		setContentView(R.layout.download_edit);
		IntentFilter counterActionFilter = new IntentFilter(
				"com.services.download");
		registerReceiver(counterActionReceiver, counterActionFilter);
		lvDownEditFiles = (ListView) findViewById(R.id.lv_down_edit_folder);
		videoList = (VideosList) DownLoadActivity.this.getApplication()
				.getApplicationContext();
		btnEditBack = (Button) findViewById(R.id.btn_dwon_edit_back);
		btnEditDelete = (Button) findViewById(R.id.btn_eidt_delete);
		btnEditBack.setOnClickListener(this);
		btnEditDelete.setOnClickListener(this);
		getIntentValue();
		viewFiles(Environment.getExternalStorageDirectory()
				+ "/EazyPlay/download/");
		downEditAdapter = new DownloadEditAdapter(DownLoadActivity.this,
				downFilesList);
		lvDownEditFiles.setAdapter(downEditAdapter);
		lvDownEditFiles.setCacheColorHint(0);
		lvDownEditFiles.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View arg1,
					int position, long id) {
				downEditAdapter.toggle(position);
			}
		});
		lvDownEditFiles.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		int count = 0;
		if (videoList.getDownloadList() != null) {
			count = videoList.getDownloadList().size();
		}
		if (downflag) {
			for (int i = count; i < oriVideoUrl.length + count; i++) {
				Queue queue = new Queue();
				queue.setId(i);
				queue.setName(title);
				queue.setSavePath(Environment.getExternalStorageDirectory()
						+ "/EazyPlay/download/"
						+ title.replaceAll("[\\p{Punct}\\p{Space}]+", "") + "/"
						+ title.replaceAll("[\\p{Punct}\\p{Space}]+", "") + "_"
						+ i + ".flv");
				queue.setUrl(oriVideoUrl[i - count]);
				queue.setDowningIntent("com.activityAction.download");
				downloadList.add(queue);
			}
		}
		onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (MODE == EDIT) {
				NormalMode();
			}else{
				this.finish();
			}
		}
		return false;
	}

	OnItemClickListener lvItemListener = new OnItemClickListener() {

		@TargetApi(8)
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			String[] loaclVideoPath = downFilesList.get(arg2).folderVideo;
			if (0 != loaclVideoPath.length) {
				Bundle b = new Bundle();
				b.putCharSequenceArray("href", loaclVideoPath);
				Intent intent = new Intent();
				intent.setClass(DownLoadActivity.this, testVideoPlayer.class);
				intent.putExtra("url", b);
				intent.putExtra("totle", loaclVideoPath.length);
				intent.putExtra("current", 1);
				intent.putExtra("title", downFilesList.get(arg2).Name);
				startActivity(intent);
			} else {
				MyToast toast = new MyToast(DownLoadActivity.this,
						"视频文件不存在，无法播放", 2500);
				toast.show();
			}
		}
	};

	private void getIntentValue() {
		Bundle getuserID = getIntent().getExtras();
		if (getuserID != null) {
			downflag = true;
			oriVideoUrl = new String[getuserID.getBundle("url").getStringArray(
					"href").length];
			oriVideoUrl = getuserID.getBundle("url").getStringArray("href");
			title = getuserID.getString("title");
		} else {
			downflag = false;
		}
		Log.e("title","title________________"+title);
	}

	private BroadcastReceiver counterActionReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			viewFiles(Environment.getExternalStorageDirectory()
					+ "/EazyPlay/download/");
			showCurrentList();
		}

	};

	private void showCurrent() {
		if (MODE == NORMAL) {
			try {
				viewFiles(Environment.getExternalStorageDirectory()
						+ "/EazyPlay/download/");
				downAdapter.setFlag(downloadService.getCurrentName());
				// lvDownFiles.setAdapter(downAdapter);
				downAdapter.notifyDataSetChanged();
				Log.e("sssss", "zoul%%%%%%%%%%%!!!!!!!!!" + count);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {

		}
	}

	/** 获取该目录下所有文件 **/
	private void viewFiles(String filePath) {
		ArrayList<FileInfo> tmp = FileHelper.getFiles(DownLoadActivity.this,
				filePath);
		if (tmp != null) {
			// 清空数据
			downFilesList.clear();
			downFilesList.addAll(tmp);
			tmp.clear();

		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				if (downflag && count == 0) {
					final DownloadDialog dialog = new DownloadDialog(
							DownLoadActivity.this, R.style.MyDialog, title,
							oriVideoUrl.length);
					dialog.show();
					Button btnOk = (Button) dialog
							.findViewById(R.id.dialog_button_ok);
					Button btnCancel = (Button) dialog
							.findViewById(R.id.dialog_button_cancel);
					btnOk.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

							// queue.setDowningIntent("com.obatu.client.DownLoadActivity");
							// queue.setCompleteIntent("com.obatu.client.installActivity");
							videoList.setDownloadListAll(downloadList);
							boolean flag = false;
							for (int i = 0; i < videoList.getDownloadList()
									.size(); i++) {
								try {
									if (downloadService.isDownLoading(i)) {
										flag = true;
										break;
									}
								} catch (RemoteException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							if (!flag) {
								if (oriVideoUrl.length == videoList
										.getDownloadList().size()) {
									try {
										downloadService.down(videoList
												.getDownloadList().get(0));
									} catch (RemoteException e) {
										e.printStackTrace();
									}
								} else {
									try {
										downloadService.down(videoList
												.getDownloadList()
												.get(videoList
														.getDownloadList()
														.size()
														- oriVideoUrl.length));
									} catch (RemoteException e) {
										e.printStackTrace();
									}
								}
							} else {
								MyToast toast = new MyToast(
										DownLoadActivity.this, "<" + title
												+ ">" + " 已加入下载队列", 2500);
								toast.show();
							}
							dialog.dismiss();
						}
					});
					btnCancel.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();
						}
					});
				}
				count++;
				showCurrentList();
				break;
			case 2:
				showCurrent();
				break;
			}
		}
	};

	private void playAnimation() {
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(800);
					Log.e("sss", "6666666666666666666666666");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(1);
			}

		}.start();
	}

	private void showCurrentList() {
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(800);
					Log.e("sss", "6666666666666666666666666");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(2);
			}

		}.start();
	}

	private void deleteFiles() {
		final int[] selectedItemIndexes = downEditAdapter
				.getSelectedItemIndexes();
		final int size = selectedItemIndexes.length;
		if (size == 0) {
			MyToast toast = new MyToast(DownLoadActivity.this, "您没有选中任何文件",
					2500);
			toast.show();
		} else {

			final ConfirmDialog dialog = new ConfirmDialog(
					DownLoadActivity.this, R.style.MyDialog, "是否确定删除已选中文件",
					0);
			dialog.show();
			Button btnOk = (Button) dialog.findViewById(R.id.dialog_confirm_button_ok);
			Button btnCancel = (Button) dialog
					.findViewById(R.id.dialog_confirm_button_cancel);
			btnOk.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					for (int i = 0; i < size; i++) {
						FileHelper.deleteFile(new File(downFilesList
								.get(selectedItemIndexes[i]).Path));
					}

					viewFiles(Environment.getExternalStorageDirectory()
							+ "/EazyPlay/download/");
					downEditAdapter.resetAllCheck();
					downEditAdapter.notifyDataSetChanged();
					dialog.dismiss();
					
				}

			});
			btnCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}

			});
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		playAnimation();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_dwon_back:
			this.finish();
			break;
		case R.id.btn_modify:
			EditMode();
			break;
		case R.id.btn_dwon_edit_back:
			NormalMode();
			break;
		case R.id.btn_eidt_delete:
			deleteFiles();
			break;
		default:
			break;
		}

	}
}
